package com.k2data.k2app.service;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.k2data.app.kmx.KmxClient;
import com.k2data.app.kmx.cond.DataRowsV4Builder;
import com.k2data.app.kmx.cond.KmxCond;
import com.k2data.app.kmx.domain.DataRows;
import com.k2data.k2app.common.KmxParams;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.DeviceCond;
import com.k2data.k2app.domain.po.Device;
import com.k2data.k2app.domain.po.DeviceOverview;
import com.k2data.k2app.domain.po.TMonitorPoint;
import com.k2data.k2app.domain.po.TMonitorVariable;
import com.k2data.k2app.mapper.DeviceMapper;
import com.k2data.k2app.mapper.DeviceOverviewMapper;
import com.k2data.k2app.mapper.TMonitorPointMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by k2data on 17-10-9.
 */
@Service
@Log4j2
public class DeviceOverviewService {

    private final DeviceOverviewMapper deviceOverviewMapper;
    private final DeviceMapper deviceMapper;
    private final KmxParams kmxParams;
    private final MyConstant myConstant;

    @Autowired
    public DeviceOverviewService(DeviceOverviewMapper deviceOverviewMapper,TMonitorPointMapper tMonitorPointMapper,
                                 DeviceMapper deviceMapper,KmxParams kmxParams,MyConstant myConstant){
        this.deviceOverviewMapper=deviceOverviewMapper;
        this.deviceMapper=deviceMapper;
        this.kmxParams=kmxParams;
        this.myConstant=myConstant;
    }
    public List<DeviceOverview> getDeviceOverviewData(long deviceId){
        DeviceCond cond =new DeviceCond();
        cond.setDeviceId(deviceId);
        Device device = deviceMapper.selectById(cond.getDeviceId());
        List<DeviceOverview> deviceOverviewList= deviceOverviewMapper.selectOverview(cond);
        return getKmxValue(deviceOverviewList,device);
    }

    public List<DeviceOverview> getPanel(long deviceId){
        DeviceCond cond =new DeviceCond();
        cond.setDeviceId(deviceId);
        Device device = deviceMapper.selectById(cond.getDeviceId());
        List<DeviceOverview> deviceOverviewList= deviceOverviewMapper.selectOverview(cond);
        List<DeviceOverview> kmxList=Lists.newArrayList();
        for (DeviceOverview deviceOverview:deviceOverviewList) {
            if(deviceOverview.getVariable().equals("speed")){
                DeviceOverview dev=deviceOverviewMapper.selectChannel(deviceId,deviceOverview.getChannelId());
                deviceOverview.setChannelId(dev.getChannelId());
                deviceOverview.setName(dev.getName());
                kmxList.add(deviceOverview);
            }
//            if(deviceOverview.getVariable().equals("speed")){
//                deviceOverview.setChannelId(deviceOverviewMapper.selectChannel(deviceId,deviceOverview.getChannelId()).getChannelId());
//                deviceOverview.setVariable(deviceOverviewMapper.selectChannel(deviceId,deviceOverview.getChannelId()).getVariable());
//                kmxList.add(deviceOverview);
//            }
        }
        return getKmxValue(kmxList,device);
    }

        private List<DeviceOverview> getKmxValue(List<DeviceOverview> deviceOverviews,Device device) {
        for (DeviceOverview var : deviceOverviews) {
            Map<String, List<String>> fields = Maps.newHashMap();
            fields.putIfAbsent(var.getFieldgroupId(), Lists.newArrayList());
            fields.get(var.getFieldgroupId()).add(var.getVariable());
            fields.get(var.getFieldgroupId()).add("$" + var.getVariable() + "_state");
            for (Map.Entry<String, List<String>> entry : fields.entrySet()) {
                List<String> ss = Splitter.on('_')
                        .trimResults()
                        .omitEmptyStrings()
                        .splitToList(device.getDeviceNo());
                DataRowsV4Builder dataRowsV4Builder = KmxCond.dataRows(kmxParams.getKmxInitParams())
                        //.url("http://117.39.60.34:28082/data-service/v4/data-rows")
                        .url(myConstant.getDataRowsRealTimeUrl())
                        .fieldGroup(entry.getKey())
                        .fields(entry.getValue())
                        .idValue(ss.get(2))
                        .idField(MyConstant.KMX_ID_FIELD_CHANNEL_ID,var.getChannelId().toString())
                        .idField(MyConstant.KMX_ID_FIELD_FACTORY_NAME, ss.get(0))
                        .idField(MyConstant.KMX_ID_FIELD_DATA_TYPE, "1")
                        .idField(MyConstant.KMX_ID_FIELD_EQUIPMENT_NAME, ss.get(1))
                        .start("now-10m")
                        .end("now")
                        .desc()
                        .size(1)
                        .page(1);

                KmxCond kmxCond = dataRowsV4Builder.build();

                DataRows dataRows = KmxClient.sync(kmxCond);
                if (dataRows.getFirstResultRows().size() > 0
                        && dataRows.getFirstResultRows().get(0).getValues() != null
                        && dataRows.getFirstResultRows().get(0).getValues().size() > 0) {
                    List<Object> values = dataRows.getFirstResultRows().get(0).getValues();
                    for (int i = 0; i < entry.getValue().size(); i = i + 2) {
                        Object o2 = values.get(i + 1);
                        Object o1 = values.get(i);
                        var.setKmxValue(new Double((o1 == null ? 0 : o1).toString()));
                        var.setLimitType(o2 == null ? "" : o2.toString());
                    }
                }
            }
        }
        return deviceOverviews;
    }

//    public List<DeviceOverview> getDeviceOverviewList(DeviceCond cond){
//        List<DeviceOverview> deviceOverviewList= deviceOverviewMapper.selectOverview(cond);
//        Map<String, Object[]> values = Maps.newHashMap();
//        List<TMonitorPoint> points = tMonitorPointMapper.selectDeviceVariable(cond);
//        Device device = deviceMapper.selectById(cond.getDeviceId());
//
//        for (DeviceOverview deviceOverview :deviceOverviewList) {
//            for (TMonitorPoint point : points) {
//                cond.setChannelId(point.getChannelId());
//                if (cond.getKmxValue() != null) {
//                    try {
//                        values = getKmxValue(point, cond, device);
//                    } catch (Exception e) {
//                        log.error("", e);
//                    }
//                }
//
//                for (TMonitorVariable var : point.getMonitorVariables()) {
//                    if("STRING".equalsIgnoreCase(var.getKmxVariableType())) {
//                        continue;
//                    }
//                    if (cond.getKmxValue() != null) {
//                        Object[] value = values.get(var.getKmxVariableNameEn());
//                        if (value == null || value.length != 2) {
//                            deviceOverview.setKmxValue(0D);
//                            continue;
//                        }
//                        String level = value[1].toString();
//                        deviceOverview.setLimitType(level);
//                        deviceOverview.setKmxValue(Double.valueOf(value[0].toString()));
//                    }
//                }
//            }
//        }
//        return deviceOverviewList;
//    }

//    private Map<String, Object[]> getKmxValue(TMonitorPoint point, DeviceCond cond, Device device) {
//        Map<String, Object[]> fieldMap = Maps.newHashMap();
//        Map<String, List<String>> fields = Maps.newHashMap();
//        for (TMonitorVariable var : point.getMonitorVariables()) {
//            fields.putIfAbsent(point.getNameEn(), Lists.newArrayList());
//            fields.get(point.getNameEn()).add(var.getKmxVariableNameEn());
//            fields.get(point.getNameEn()).add("$" + var.getKmxVariableNameEn() + "_state");
//        }
//
//        for (Map.Entry<String, List<String>> entry : fields.entrySet()) {
//            List<String> ss = Splitter.on('_')
//                    .trimResults()
//                    .omitEmptyStrings()
//                    .splitToList(device.getDeviceNo());
//            DataRowsV4Builder dataRowsV4Builder = KmxCond.dataRows(kmxParams.getKmxInitParams())
//                    .url(myConstant.getDataRowsRealTimeUrl())
//                    .fieldGroup(entry.getKey())
//                    .fields(entry.getValue())
//                    .idValue(ss.get(2))
//                    .idField(MyConstant.KMX_ID_FIELD_CHANNEL_ID, cond.getChannelId() == null ? "" : cond.getChannelId().toString())
//                    .idField(MyConstant.KMX_ID_FIELD_FACTORY_NAME, ss.get(0))
//                    .idField(MyConstant.KMX_ID_FIELD_DATA_TYPE, "1")
//                    .idField(MyConstant.KMX_ID_FIELD_EQUIPMENT_NAME, ss.get(1))
//                    .start("now-10m")
//                    .end("now")
//                    .desc()
//                    .size(1)
//                    .page(1);
//
//
//            KmxCond kmxCond = dataRowsV4Builder.build();
//
//            DataRows dataRows = KmxClient.sync(kmxCond);
//            if (dataRows.getFirstResultRows().size() > 0
//                    && dataRows.getFirstResultRows().get(0).getValues() != null
//                    && dataRows.getFirstResultRows().get(0).getValues().size() > 0) {
//                List<Object> values = dataRows.getFirstResultRows().get(0).getValues();
//
//                for (int i = 0; i < entry.getValue().size(); i = i + 2) {
//                    String field = entry.getValue().get(i);
//                    Object o2 = values.get(i + 1);
//                    Object o1 = values.get(i);
//                    fieldMap.put(field, new Object[]{o1 == null ? 0 : o1, o2 == null ? "" : o2});
//                }
//            }
//        }
//        return fieldMap;
//    }
}
